﻿package
{
	
	import flash.display.MovieClip;
	import flash.display.Shape;
	import flash.events.IOErrorEvent;
	import flash.events.MouseEvent;
	import flash.events.ProgressEvent;
	import flash.events.SecurityErrorEvent;
	import flash.net.URLVariables;
	import flash.net.URLRequest;
	import flash.net.URLRequestMethod;
	import flash.net.URLLoader;
	import flash.net.URLLoaderDataFormat;
	import flash.events.Event;
	import flash.text.TextFieldAutoSize;
	import flash.display.Loader;
	import flash.filesystem.File;
	import flash.filesystem.FileStream;
	import flash.filesystem.FileMode;
	import flash.net.Socket;
	
	public class Connection extends MovieClip
	{
		
		//variaveis de socket
		var socket:Socket;
		var ip:String = "producao-01.sevengame.com";
		var port:int = 66;
		
		//variaveis de controle de string
		var txtLogin:String;
		var txtSenha:String;
		
		public var retornoMsg:String;
		
		public function Connection()
		{
			// constructor code
			this.socket = new Socket();
			
			this.socket.connect(ip, port);
			
			this.socket.addEventListener(ProgressEvent.SOCKET_DATA, socketData, false, 0, true);
			this.socket.addEventListener(Event.CONNECT, clicouBTLogar, false, 0, true);
			this.socket.addEventListener(Event.CLOSE, fecharSocket, false, 0, true);
			this.socket.addEventListener(IOErrorEvent.IO_ERROR, socketError, false, 0, true);
			this.socket.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityError, false, 0, true);
		
		}
		
		function enviarTexto(enviar:String):void
		{
			this.socket.writeUTFBytes(enviar + "\n");
			this.socket.flush();
		}
		
		/*------------------------------------*/
		
		function retornarString(msg:String):void
		{
			retornoMsg = msg;
		
		}
		
		function enviarDesenho(pontX:int, pontY:int, ferramenta:String):void
		{
			//trace(pontX + "/" + pontY + "/" + ferramenta);
			pontX, pontY, ferramenta += "\n";
			this.socket.writeUTFBytes("zzzdesenho" + "/" + pontX + "/" + pontY + "/" + ferramenta);
			this.socket.flush();
		}
		
		public function recebeDesenho():Boolean
		{
			if (retornoMsg != null)
			{
				
				if (this.retornoMsg.charAt(0))
				{
					return true;
					trace(true);
					
				}
				return false;
			}
			return false;
		
		}
		
		/*Função responsavel pelo Socket*/
		function clicouBTLogar(e:Event):void
		{
			trace("Connected: " + e);
		}
		
		function socketData(e:Event):void
		{
			trace("Recebendo dados: " + e);
			retornarString(this.socket.readUTFBytes(this.socket.bytesAvailable));
		}
		
		function fecharSocket(e:Event):void
		{
			retornoMsg = "Conexão fechada, tente mais tarde";
		}
		
		function socketError(e:IOErrorEvent):void
		{
			this.socket.close();
			retornoMsg = "Servidor de login offline"; /*+ e*/
		}
		
		function securityError(e:SecurityErrorEvent):void
		{
			trace("SecurityError: " + e);
		}
	/*------------------------------*/
	
	}

}